var JSObject = {

    selected_row_id:null,
    selected_contact_ids:[],
    objGrid:null,
    person_info_id:null,

    init:function () {
        var self = this;

        var btn_actions = [];

        if(inArray('PX',permissions)){
            btn_actions.push({type:'buttom', name:'Export Selected', bclass:'export', onpress:self.handleGridEvent});
            btn_actions.push({separator:true});
        }
        if(inArray('PX',permissions)){
            btn_actions.push({type:'buttom', name:'Export All', bclass:'export', onpress:self.handleGridEvent});
            btn_actions.push({separator:true});
        }
        btn_actions.push({type:'select',name: 'Filter Status', id: 'filter_status' ,bclass: 'filter',onchange:self.handleGridEvent,options:sms_status});

        self.objGrid = $('#flex').flexigrid({
            url:$('#table-url').val(),
            reload_after_add:true,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:80, sortable:true, align:'left', hide:true},
                {display:'Date', name:'created', width:120, sortable:true, align:'left', hide:false},
                {display:'Phone Number', name:'phone_number', width:120, sortable:true, align:'left', hide:false},
                {display:'Message', name:'message', width:350, sortable:true, align:'left', hide:false},
                {display:'SMS Status', name:'status', width:80, sortable:true, align:'left', hide:false},
                {display:'Cost', name:'cost', width:80, sortable:true, align:'left', hide:false}
           ],
            formFields:btn_actions,
            checkboxSelection:true,
            editablegrid:{
                use:false,
                url:$('#table-editable-url').val(),
                add:inArray('A',permissions),
                edit:inArray('E',permissions)
            },
            columnControl:false,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300,
            subgrid:{
                use:false
            }
        });
    },

    handleGridEvent:function (com, grid, json) {
        if (com == 'Export All') {
            JSObject.export_history(null, 'all');
        }
        else if (com == 'Export Selected') {
            var r = FlexObject.rowSelectedCheck(JSObject.objGrid,grid);
            if(r){
                JSObject.export_history(FlexObject.getSelectedRowIds(grid), 'selected');
            }
        }
        else if (com == 'Filter Status') {
            JSObject.filterGrid(json);
        }

        /*if (com == 'New') {
            JSObject.objGrid.flexBeginAdd();
        }
        else if (com == 'Edit') {
            var r = FlexObject.rowSelectedCheck(JSObject.objGrid,grid,1);
            if(r){
                var row = FlexObject.getSelectedRows(grid);
                JSObject.objGrid.flexBeginEdit(row[0]);
            }
        }
        else if (com == 'Save') {
            JSObject.objGrid.flexSaveChanges();
        }
        else if (com == 'Cancel') {
            JSObject.objGrid.flexCancel();
        }
        else if (com == 'Delete') {
            var r = FlexObject.rowSelectedCheck(JSObject.objGrid,grid);
            if(r){
                JSObject.delete_(grid);
            }
        }
        else if (com == 'Import Customers From File') {
            JSObject.import_customers_to_group();
        }

        else if (com == 'Assign Contacts To Group') {
            var r = FlexObject.rowSelectedCheck(JSObject.objGrid,grid);
            if(r){
                var row_ids = FlexObject.getSelectedRowIds(grid);
                JSObject.assignContactsToGroup(row_ids);
            }
        }*/
    },

    filterGrid:function(json){
        var filter_status = $("#filter_status").val();
        $(JSObject.objGrid).flexOptions({
            params: [
                {name: 'filter_status', value: filter_status}
            ]
        }).flexReload();
    },


    export_history:function (row_ids, export_type) {
        var self = this;
        var data_ids = '';
        console.log(typeof row_ids);
        if (typeof row_ids != null) {
            for (var x in row_ids) {
                data_ids += '' + row_ids[x] + ','
            }
        }
        $("#export-form #export_type").val(export_type);
        $("#export-form #export_ids").val(data_ids);
        $("#export-form #export_filter_status").val($("#filter_status").val());
        window.open('', "ExportWindow", "menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        //document.getElementById('popUpform').submit();
        $("#export-form").submit();

    },


    delete_:function (grid) {
        var self = this;
        var url = $('#table-delete-url').val();
        jLib.do_delete(url, grid,function(response){
            if(response.code == 0){
                FlexObject.removeGridRows(grid);
                self.objGrid.flexNotify('Status', response.msg, 'success');
            }
            else if(response.code == 1){
                self.objGrid.flexNotify('Status', response.msg, 'error');
            }
        });
    },

    assignContactsToGroup:function (contact_ids) {
        var self = this;
        self.selected_contact_ids = contact_ids;
        $("#assign_contact_group_modal form")[0].reset();
        $('#assign_contact_group_modal').modal({
            backdrop: 'static',
            show: true,
            keyboard: true
        });
    },

    do_assign_contact_to_group:function(){
        var self = this;

        var save = {
            group_id: $("#selected_assign_group").val(),
            contact_ids:self.selected_contact_ids
        }

        var url = $('#assign-group-url').val();
        var query = 'data=' + encodeURIComponent(JSON.stringify(save));

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    jLib.serverSuccess(txt);
                    $(self.objGrid).flexReload();
                    $("#close-assign_contact_group").click();
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt,false);
                }
            },
            error:function (xhr) {
                jLib.serverError();
            }
        });
    },


    import_customers_to_group:function(){
        var self = this;
        var filter_c_group = parseInt($("#filter_c_group").val());
        var filter_name = $("#filter_c_group option:selected").text();
        var txt = '';
        if(filter_c_group == -1){
            txt = "The contacts you are about to import will have No Group associated to them. Click OK if you want to proceed or Cancel if you want to quit.";
        }
        else{
            txt = "The contacts you are about to import will be added to the group filtered "+filter_name+". Click OK if you want to proceed or Cancel if you want to quit.";
        }
        jConfirm(txt, 'Confirm', function(confirmation) {
            if(confirmation){
                if(filter_c_group == -1){
                    filter_c_group = 0;
                }
                self.selected_row_id = filter_c_group;
                $("#import_contact_group_btn").click();
            }
        });
    },

    import_extra_param:function(p){
        var self = this;
        //You can even change the data to pass dynamically before this function get called by the file upload manager
        var params={
            contact_group_id:self.selected_row_id
        };
        return params;
    },

    import_callback:function(p){
        var self = this;
        $(self.objGrid).flexReload();
    }
};

/* when the page is loaded */
$(document).ready(function () {
    JSObject.init();
});

function func_extra_param(){
    return JSObject.import_extra_param();
}

function func_callback(){
    return JSObject.import_callback();
}